package com.tuxing.draa_data.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

/**
 * 格式转换的工具类
 * 用来转换数据的格式
 *
 * @Author yqliang
 * @Date 2019/12/11 15:21
 * @Version 1.0
 **/
@Slf4j
public class ConvertUtil {


    /**
     * 任意类型转换成Int型
     *
     * @param object 传入的值
     * @return int型的值
     */
    public static int objToInt(Object object) {
        return objToInt(object, 0);
    }

    /**
     * 转换成int类型的数据
     * 任意类型的对象，转换成int类型的数据，如果转换失败，返回默认的value
     *
     * @Author yqliang
     * @Param object: 入参对象
     * @Param defaultValue: 默认返回值
     * @return: int
     * @Date 2019/12/11
     **/
    public static int objToInt(Object object, int defaultValue) {
        int ret = defaultValue;
        if (object == null) {
            return ret;
        }
        try {
            String tmp = object.toString();
            int dotIndex = tmp.indexOf(".");
            if (dotIndex > 0) {
                tmp = tmp.substring(0, dotIndex);
            }
            tmp = tmp.replace(",", "");
            ret = Integer.parseInt(tmp);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
        return ret;
    }

    /**
     * 将任意类型转换成boolean
     *
     * @Author yqliang
     * @Param object:  传入的值
     * @Param defaultValue: 默认的值
     * @return: java.lang.Boolean
     * @Date 2019/12/11
     **/
    public static Boolean objToBoolean(Object object, Boolean defaultValue) {
        boolean ret = defaultValue;
        if (object == null) {
            return ret;
        }
        try {
            ret = Boolean.parseBoolean(object.toString());
        } catch (Exception ignored) {

        }
        return ret;
    }

    /**
     * 将任意类型转换成decimal
     *
     * @param object 传入的值
     * @return decimal类型的值
     */
    public static BigDecimal objToDec(Object object) {
        return objToDec(object, BigDecimal.ZERO);
    }

    /**
     * 将任意类型转换成decimal
     *
     * @param object       传入的值
     * @param defaultValue 默认值
     * @return decimal类型的值
     */
    public static BigDecimal objToDec(Object object, BigDecimal defaultValue) {
        BigDecimal ret = defaultValue;
        if (object != null) {
            try {
                ret = new BigDecimal(object.toString());
                ret = ret.setScale(2, BigDecimal.ROUND_HALF_UP);
            } catch (NumberFormatException e) {
                log.error(e.getMessage(), e);
                return defaultValue;
            }
        }
        if (ret.compareTo(BigDecimal.ZERO) == 0) {
            ret = BigDecimal.ZERO;
        }
        return ret;
    }


    /**
     * @Title object 转实体对象
     * @Des
     * @Author yqliang
     * @Param object  对象
     * @Param className:  实体的class
     * @Return T  转换的结果，如果转换失败，则会返回null！！
     * @Date 2020/4/14
     **/
    public static <T> T objToEntity(Object object, Class<T> className) {
        T obj = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            obj = objectMapper.convertValue(object, className);
        } catch (Exception e) {
            log.error("转换错误：" + e.getMessage(), e);
        }
        return obj;
    }


    /**
     * 任意类型转换成long型
     *
     * @param object 传入的值
     * @return int型的值
     */
    public static Long objToLong(Object object) {
        return objToLong(object, 0L);
    }

    /**
     * 转换成int类型的数据
     * 任意类型的对象，转换成int类型的数据，如果转换失败，返回默认的value
     *
     * @Author yqliang
     * @Param object: 入参对象
     * @Param defaultValue: 默认返回值
     * @return: int
     * @Date 2019/12/11
     **/
    public static Long objToLong(Object object, Long defaultValue) {
        Long ret = defaultValue;
        if (object == null) {
            return ret;
        }
        try {
            ret = Long.parseLong(object.toString());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
        return ret;
    }

    //region byte和String的转换

    /**
     * byte[]转String
     *
     * @param byteArray 字节
     * @return string
     */
    public static String byteToString(byte[] byteArray) {
        String ret = "";
        if (byteArray == null) {
            return ret;
        }

        try {
            ret = new String(byteArray, StandardCharsets.UTF_8);
        } catch (Exception e) {
            ret = e.getMessage();
        }

        return ret;
    }

    /**
     * string转byte
     *
     * @param value string
     * @return 字节
     */
    public static byte[] stringToByte(String value) {
        byte[] ret = new byte[]{};
        if (StringUtils.isNotBlank(value)) {

            try {
                ret = value.getBytes(StandardCharsets.UTF_8);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
        return ret;
    }


    //region 字符串转换成CSV的字符串

    /// <summary>
    /// 将字符串格式化成csv的字符串。
    /// 如果字符串中间有逗号需要在两遍设置双引号；
    /// 如果本身有双引号，需要将内部的双引号变成成对。
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static String stringToCsvString(String obj) {
        if (Strings.isNullOrEmpty(obj))
            return "";

        String ret = obj.replace("\"", "\"\"");
        ret = ret.contains(",")
                || ret.contains("\"\"")
                || ret.contains("\r\n")
                || ret.contains("\n\n")
                || ret.contains("\r")
                || ret.contains("\n")
                ? "\"" + ret + "\"" : ret;

        return ret;
    }

    /**
     * 处理特殊字符
     */
    public static String checkIllegalCharacter(String str){
        if(StringUtils.isBlank(str)){
            return str;
        }
        char[] charArr = str.toCharArray();
        StringBuilder newValue = new StringBuilder();
        for (char value : charArr) {
            switch (value) {
                case '\0':
                    newValue.append("\\0");
                    break;
                case '\n':
                    newValue.append("\\n");
                    break;
                case '\r':
                    newValue.append("\\r");
                    break;
                case '\'':
                    newValue.append("\\'");
                    break;
                case '"':
                    newValue.append("\\\"");
                    break;
                case '\\':
                    newValue.append("\\\\");
                    break;
                case '%':
                    newValue.append("\\%");
                    break;
                case '_':
                    newValue.append("\\_");
                    break;
                default:
                    newValue.append(value);
                    break;
            }
        }
        return newValue.toString();

    }


//    /**
//     * 转码
//     *
//     * @author yqliang
//     * @param str
//     * @return java.lang.String
//     * @date 2020/10/12
//     **/
//    public static String ConverUtf8(String str){
//        if (StringUtils.isBlank(str)){
//            return str;
//        }
//        try {
//            str = URLDecoder.decode(str, Contants.URL_ENCODE);
//        }catch (Exception e){
//            log.error("解码失败");
//        }
//
//        return str;
//    }


    /**
     * 多个byte[] 合并成一个
     *
     */
    public static byte[] byteMergerAll(byte[]... values) {
        int length_byte = 0;
        for (byte[] value : values) {
            length_byte += value.length;
        }
        byte[] all_byte = new byte[length_byte];
        int countLength = 0;
        for (byte[] b : values) {
            System.arraycopy(b, 0, all_byte, countLength, b.length);
            countLength += b.length;
        }
        return all_byte;
    }

}
